import React, { useState, useCallback } from "react";
import { NextPage } from "next";
import { message, Modal, Popconfirm } from "antd";

import { AdminLayout } from "@/layout";
import { SPTDataTable } from "@/components/SPTDataTable";
import { MailApi } from "@/api/mail";
import dayjs from "dayjs";

const Mail: NextPage = () => {
  const [loading, setLoading] = useState(false);
  const [mails, setMails] = useState(null);
  const [curr, setCurr] = useState<IMail>(null);
  const [visible, setVisible] = useState(false);
  const [params, setParams] = useState(null);
  const getMails = useCallback((params) => {
    setLoading(true);
    return MailApi.getMails(params).then((res) => {
      setLoading(false);
      setMails(res[0]);
      setParams(params);
      return res;
    });
  }, []);

  const deleteMail = (id) => {
    MailApi.deleteMail(id).then((res) => {
      message.success("删除成功");
      getMails(params);
    });
  };
  const columns = [
    {
      title: "发件人",
      key: "from",
      dataIndex: "from",
    },
    {
      title: "收件人",
      key: "to",
      dataIndex: "to",
    },
    {
      title: "主题",
      key: "subject",
      dataIndex: "subject",
    },
    {
      title: "内容",
      key: "html",
      render: (_, record) => (
        <a
          onClick={() => {
            setCurr(record);
            setVisible(true);
          }}
        >
          点击查看
        </a>
      ),
    },
    {
      title: "发送时间",
      key: "createAt",
      render: (_, record) =>
        dayjs(record.publishAt).format("YYYY-MM-DD hh:mm:ss"),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Popconfirm
          onConfirm={() => deleteMail(record.id)}
          okText="删除"
          cancelText="取消"
          title="删除邮件"
        >
          <a>删除</a>
        </Popconfirm>
      ),
    },
  ];
  return (
    <AdminLayout>
      <Modal
        closable={true}
        visible={visible}
        title="发送内容"
        footer={null}
        width={820}
        onCancel={() => setVisible(false)}
      >
        <div
          className="markdown"
          style={{ overflow: "auto !important" }}
          dangerouslySetInnerHTML={{
            __html: curr?.html,
          }}
        ></div>
      </Modal>
      <SPTDataTable
        defaultTotal={0}
        data={mails}
        onSearch={getMails}
        searchFields={[
          {
            label: "发件人",
            field: "from",
            msg: "请输入发件人",
          },
          {
            label: "收件人",
            field: "to",
            msg: "输入收件人",
          },
          {
            label: "主题",
            field: "subject",
            msg: "请输入主题",
          },
        ]}
        columns={columns}
      />
    </AdminLayout>
  );
};

export default Mail;
